%   Copyright (c) [2023] [423109070325付志峰]
%   [春天的高等数学代码库] is licensed under Mulan PSL v2.
%   You can use this software according to the terms and conditions of the Mulan PSL v2. 
%   You may obtain a copy of Mulan PSL v2 at:
%            http://license.coscl.org.cn/MulanPSL2 
%   THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.  
%   See the Mulan PSL v2 for more details. 
clc; clear all;
syms x                       % 定义变量
f = @(x) x^2 - x -1;         % 求解方程（在此处输入方程哦O.o）
a = 1; b = 10;                % 初始的区间上下限
n = 10;                       % 迭代次数
w = 0.0005;                    % 误差要求（很重要哦）

while f(a) * f(b) < 0        % 存在根
    x_0 = (a+b)/2            % 计算中点，开始二分
    
    if f(x_0) == 0           % 零点即中点
        break;
    end
    
    if f(a) * f(x_0) < 0     % 零点在左边的区间
        b = x_0;
    else                     % 零点在右边的区间
        a = x_0;
    end
    
    n = n+1
    
    if abs(a - b) < w       % 判断是否满足精度条件
        x_0                 % 最终得到的近似解
        n = n+1             % 迭代总次数
        break;
    end
    
end
